import numpy as np  
import pandas as pd  
import tensorflow as tf  
from sklearn.model_selection import train_test_split  
from sklearn.preprocessing import StandardScaler  
import matplotlib.pyplot as plt  
  
# 假设已经准备好带钢产品的规格数据、工艺参数和硬度数据  
# 请根据实际情况导入数据  
X = pd.read_csv('data.csv', usecols=[2, 6, 7, 9])  # 选取四个特征值  
y = pd.read_csv('data.csv', usecols=[12])         # 硬度数据  
  
# 数据预处理：标准化特征值  
scaler = StandardScaler()  
X_scaled = scaler.fit_transform(X)  
  
# 划分数据集为训练集和测试集  
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)  
  
# 构建神经网络模型  
model = tf.keras.Sequential([  
    tf.keras.layers.Dense(128, activation='relu', input_shape=(4,), kernel_regularizer=tf.keras.regularizers.l2(0.01)),  
    tf.keras.layers.Dropout(0.2),  
    tf.keras.layers.Dense(64, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),  
    tf.keras.layers.Dense(32, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),  
    tf.keras.layers.Dense(1)  
])  
  
# 编译模型，使用adam优化器和平均绝对误差损失函数  
model.compile(optimizer='adam', loss='mae')  
  
# 准备回调函数，包括早停法  
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)  
  
# 训练模型  
history = model.fit(X_train, y_train, epochs=200, batch_size=32, validation_data=(X_test, y_test), callbacks=[early_stopping], verbose=0)  
  
# 绘制训练和验证损失的图  
plt.plot(history.history['loss'], label='Training loss')  
plt.plot(history.history['val_loss'], label='Validation loss')  
plt.title('Training and Validation Loss')  
plt.xlabel('Epoch')  
plt.ylabel('Loss')  
plt.legend()  
plt.show()  
  
# 评估模型性能  
loss = model.evaluate(X_test, y_test)  
print("模型在测试集上的损失（MAE）:", loss)